<?php


namespace App\Models\CacheModel\zlcr2;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zlcr2UserSameQuestion extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr2_user_same_question';
    protected $cacheModel = 'question_answer.question_same';

    /**
     * 问题蹭看
     * @param array $data
     * @return bool
     */
    public function SaveData(array $data)
    {
        try
        {
            // data['type'] 1=>别人的提问 2=>猜你想问
            $this->save($data);
            // 添加至我的问答-蹭看列表
            $this->listDataAdd($data['same_qid'], [$data['uid'] => $data['create_time']], $data['type']);

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('问答 Zlcr2UserSameQuestion model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取问答 同问用户uids
     * @param string $qid
     * @param int $type 1=>别人的提问 2=>猜你想问
     * @return array
     * @throws \Exception
     */
    public function getQuestionSameUserIds(string $qid, int $type): array
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $qid)
            ->setPage(-1)
            ->setListKeyType($type)// 类型 1=>别人的提问 2=>猜你想问
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($qid, $type)
            {
                try
                {
                    $data = $this->where(['same_qid' => $qid, 'type' => $type])->column('create_time', 'uid');
                    $resData = [];
                    foreach ($data as $uid => $createTime)
                    {
                        $resData[$uid] = ['create_time' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'create_time', 0);

        return $resData['data'] ? array_keys($resData['data']) : [];
    }

    /**
     * 获取用户是否蹭看及蹭看数
     * @param int $uid
     * @param string $qid
     * @return array
     * @throws \Exception
     */
    public function getQuestionSameNumAndIsSame(int $uid, string $qid): array
    {
        $sameUids = $this->getQuestionSameUserIds($qid, 1);

        return [
            'is_same' => in_array($uid, $sameUids, false) ? true : false,
            'same_num' => count($sameUids)
        ];
    }
}
